using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections.Generic;

namespace Guide
{
    public class TeachControl : UFrame.BridgeUI.BridgeUIControl
    {
        [SerializeField]
        protected Text m_stepNameText;
        [SerializeField]
        protected Button m_hideBtn;
        [SerializeField]
        protected GameObject m_noticeHand;

        protected Vector3[] m_cornors = new Vector3[4];
        protected Vector4 m_rectPos = Vector4.zero;
        protected Material m_material;
        protected RectTransform m_targetTrans;
        protected float m_startTime;
        protected Vector3 m_worldPos;
        protected float m_redios;
        protected string teachType;
        protected float m_delyTime;
        protected string m_guidingText;
        protected int m_guidingTextId;


        protected override void OnInititalize()
        {
            //HideBtn_RectTransform
            TryStartGuide();
        }

        protected override void OnUnInitialize()
        {
        }

        private void TryStartGuide(params object[] _param)
        {
            m_startTime = Time.time;
            m_guidingTextId = 0;
            m_guidingText = "";
            m_stepNameText.text = "";

            //var currentStep = CManager.GuideManager.Instance.GetCurrentGuideStep();
            //if (currentStep != null)
            //{
            //    m_guidingText = currentStep.stepName;
            //}

            teachType = "";

            if (_param.Length > 0)
            {
                teachType = _param[0].ToString();
            }

            m_delyTime = 0;
            if (_param.Length > 1)
            {
                float.TryParse(_param[1].ToString(), out m_delyTime);
            }

            if (teachType == "hit_ui" && _param.Length > 1)
            {
                string sourcePath = "";
                if (_param.Length > 2)
                {
                    sourcePath = _param[2].ToString();
                }
                //var target = UIManager.Instance.UiRoot.Find(sourcePath);
                //if (target == null)
                //{
                //    Debug.LogError("failed find target path:" + sourcePath, UIManager.Instance.UiRoot);
                //    OnClickTarget(null);
                //    return;
                //}
                //HideMaskPort();
                //m_targetTrans = target as RectTransform;
                //TimerManager.Instance.AddAction(this, ShowMaskByTargetTrans, 0.02f, ref m_focusTimer, true);
            }
            else if (teachType == "hit_pos" && _param.Length > 3)
            {
                var worldPosStrArray = _param[2].ToString().Split('$');
                var redioStr = _param[3].ToString();
                m_worldPos = Vector3.zero;
                if (worldPosStrArray.Length >= 3 && float.TryParse(redioStr, out m_redios))
                {
                    float.TryParse(worldPosStrArray[0], out m_worldPos.x);
                    float.TryParse(worldPosStrArray[1], out m_worldPos.y);
                    float.TryParse(worldPosStrArray[2], out m_worldPos.z);

                    HideMaskPort();
                    //TimerManager.Instance.AddAction(this, ShowMaskByWorldPos, 0.02f, ref m_focusTimer, true);
                }
                else
                {
                    Debug.LogError("failed parse args:" + _param[2] + "-" + _param[3]);
                    OnClickTarget(null);
                }
            }
            else
            {
                Debug.LogError("error teachType:" + teachType + " _param.Length:" + _param.Length);
                OnClickTarget(null);
            }
        }

        private void ShowMaskByTargetTrans()
        {
            if (CheckDelyTimer())
                return;

            if(!m_targetTrans)
            {
                //UIManager.Instance.CloseUI(UIDefine.UIInfo.TeachView);
				Debug.LogError("target trans empty!");
                //GuideManager.Instance.StopGuideSystem();
                return;
            }

            m_hideBtn.image.rectTransform.position = m_targetTrans.position;
            m_hideBtn.image.rectTransform.sizeDelta = m_targetTrans.sizeDelta;
            m_noticeHand.gameObject.SetActive(true);
            RefreshMaterial();
            RefreshText();
        }

        private bool CheckDelyTimer()
        {
            float timerOffset = Time.time - m_startTime;
            if (timerOffset < m_delyTime)
            {
                return true;
            }
            else if (timerOffset > m_delyTime + 10)
            {
                //m_focusTimer.Stop(ref m_focusTimer);
            }
            return false;
        }

        private void RefreshMaterial()
        {
            var hideBtnRect = m_hideBtn.image.rectTransform;
            m_rectPos.x = hideBtnRect.localPosition.x - hideBtnRect.sizeDelta.x * 0.5f;
            m_rectPos.y = hideBtnRect.localPosition.y - hideBtnRect.sizeDelta.y * 0.5f;
            m_rectPos.z = hideBtnRect.sizeDelta.x;
            m_rectPos.w = hideBtnRect.sizeDelta.y;
            m_material.SetVector("_Rect", m_rectPos);
        }

        private void ShowMaskByWorldPos()
        {
            if (CheckDelyTimer())
                return;

            Vector3 ptViewport = Camera.main.WorldToViewportPoint(m_worldPos);
            var hideBtnRect = m_hideBtn.image.rectTransform;
            //获取父UI的长宽，注意不是Screen.Width、Screen.heigt
            RectTransform rtParent = hideBtnRect.parent.GetComponent<RectTransform>();
            var centerPos = Vector2.zero;
            centerPos.x = rtParent.pivot.x * rtParent.rect.width;
            centerPos.y = rtParent.pivot.y * rtParent.rect.height;
            //设置锚点位置，锚点在左下角
            hideBtnRect.anchoredPosition = new Vector2(ptViewport.x * rtParent.rect.width, ptViewport.y * rtParent.rect.height) - centerPos;
            hideBtnRect.sizeDelta = new Vector2(m_redios, m_redios);
            m_noticeHand.gameObject.SetActive(true);
            RefreshMaterial();
            RefreshText();
        }

        private void RefreshText()
        {
            var timeSpan = Time.time - m_startTime - m_delyTime;
            var num = Mathf.CeilToInt(timeSpan * 10);
            num = Mathf.Clamp(num, 0, m_guidingText.Length);
            m_stepNameText.text = m_guidingText.Substring(0,num);
        }

        private void HideMaskPort()
        {
            m_noticeHand.gameObject.SetActive(false);
            m_rectPos = Vector4.zero;
            m_material.SetVector("_Rect", m_rectPos);
        }

        private void OnClickTarget(PointerEventData data)
        {
            //UIManager.Instance.CloseUI(UIDefine.UIInfo.TeachView);
            List<RaycastResult> results = new List<RaycastResult>();
            EventSystem.current.RaycastAll(data, results);
            GameObject current = data.pointerCurrentRaycast.gameObject;
            for (int i = 0; i < results.Count; i++)
            {
                if (current != results[i].gameObject)
                {
                    data.pointerClick = results[i].gameObject;
                    ExecuteEvents.Execute(results[i].gameObject, data, ExecuteEvents.pointerClickHandler);
                    //RaycastAll后ugui会自己排序，如果你只想响应透下去的最近的一个响应，这里ExecuteEvents.Execute后直接break就行。
                }
            }
        }

    }
}
